/**
 * 新增派工单
 */
$(function() {

    addArrangeInfo();
    function addArrangeInfo() {
        layui.use(['table', 'form', 'element', 'laydate','layer','tree','util'], function () {
            var $ = layui.$;
            var table = layui.table;
            var form = layui.form;
            var element = layui.element;
            var laydate = layui.laydate;
            var layer = layui.layer;
            var util = layui.util;
            var tree = layui.tree;
            console.log("进入addArrangeInfo.js文件");

            //自动获取“机构”信息并显示在指定位置
            $.ajax({
                type: "GET",
                url: "/arrangeInfo/getArrangeOrg",
                dataType: "JSON",
                success: function(result) {
                    console.log("成功获取");
                    console.log(result[0]);
                    console.log(result[0].department_name);
                    document.getElementById('department_name').value=result[0].department_name;
                    document.getElementById('department_phone_number').value=result[0].department_phone_number;
                    document.getElementById('department_settlement_code').value=result[0].department_settlement_code;
                    document.getElementById('department_address').value=result[0].department_address;
                    document.getElementById('department_region_code').value=result[0].department_region_code;
                    document.getElementById('department_settlement_scope').value=result[0].department_settlement_scope;
                    document.getElementById('department_corporate').value=result[0].department_corporate;
                    document.getElementById('department_notification_date').value=result[0].department_notification_date;
                    document.getElementById('department_first_settle_date').value=result[0].department_first_settle_date;
                    document.getElementById('department_first_time').value=result[0].department_first_time;
                    document.getElementById('department_change_time').value=result[0].department_change_time;
                }
            });

            // 折叠面板
            element.on('collapse(test)', function(data) {
                layer.msg('展开状态：' + data.show);
            });
            //老人表格渲染
            var tableIns = table.render({
                elem: '#elderArrangeList'
                ,id:'elderArrange'
                , url: '/elderInfo/showElderInfo'
                // , toolbar:true
                // , totalrow:true
                , height: 350
                , cellMinWidth: 80//全局定义常规单元格的最小宽度，layui 2.2.1 新增
                , request: {
                    pageName: 'pn' //页码的参数名称，默认：page
                    , limitName: 'limit' //每页数据量的参数名，默认：limit
                }
                , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                    return {
                        "code": 0, //解析接口状态
                        "msg": '', //解析提示文本
                        "count": res.total, //解析数据长度
                        "data": res.list //解析数据列表
                    }
                }
                , cols: [[
                    {field: 'name', width:100,title: '姓名'}
                    , {field: 'gender', title: '性别'}
                    , {field: 'id_number', width: 200, title: '身份证号'}
                    , {field: 'phone_number', width: 150, title: '联系方式'}
                    , {field: 'serv_org', width: 150, title: '服务机构', sort: true}
                    , {field: 'last_serv_org', width: 150, title: '上一家服务机构', sort: true}
                    , {field: 'js_id', title: '结算ID'}
                    , {field: 'person_level', title: '等级', sort: true}
                    , {field: 'sbcard_id', width: 150, title: '社保卡号'}
                    , {field: 'ybid', width: 150, title: '医保卡号'}
                    , {field: 'age', title: '年龄', sort: true}
                    , {field: 'person_catagory', width: 120, title: '人员性质', sort: true}
                    , {field: 'contact_people', title: '联系人'}
                    , {field: 'care_assistant', title: '护理员'}
                    , {field: 'fwaddress', width: 200, title: '服务地址'}
                    , {field: 'fwaddresscj', width: 200, title: '接受服务地址所在村居'}
                    , {field: 'fwjz', width: 200, title: '接受服务地址所在街镇'}
                    , {field: 'daiyu_start_date', width: 200, title: '待遇开始日'}
                    , {field: 'daiyu_due_date', width: 200, title: '待遇到期日'}
                    , {field: 'assess_type', width: 200, title: '评估类型'}
                    , {field: 'ser_situation', width: 200, title: '服务状态'}
                    , {fixed: 'right', toolbar: '#Confirm', width:80,title: '选中'}
                ]]
                , page: true
            });

            // 老人搜索功能
            var $ = layui.$, active = {
                // 信息页面-搜索功能
                search: function(){
                    var send_name = $('#elder_name');
                    var send_ybid = $('#elder_yb_id');
                    var send_id=$('#elder_id');
                    console.log("搜索的老人姓名是"+send_name.val());
                    console.log("搜索的医保ID是"+send_ybid.val());
                    console.log("搜索的身份证号是"+send_id.val());

                    //执行重载
                    table.reload('elderArrange', {
                        url: '/arrangeInfo/searchArrangeElder',
                        method:'post',
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }
                        ,where: {
                            elderName: send_name.val(),
                            Ybid: send_ybid.val(),
                            ID:send_id.val()
                        }
                    }, 'data');
                }
            };
            $('.SearchElder .layui-btn').on('click', function () {
                console.log("新增订单页面：触发按键");
                var type = $(this).data('type');
                console.log("type:"+type);
                active[type] ? active[type].call(this) : '';
                console.log("结束");
            });

            // 老人表格监听是否选择了确定按钮
            table.on('tool(elderArrange)', function(obj) {
                console.log("按下确定按钮");
                var data = obj.data;
                console.log(data.gender);
                console.log(gender);
                if (obj.event === 'sure') {
                    layer.confirm('是否确定为该老人添加派工订单', function(index){
                        $.ajax({
                            success:function(){
                                console.log("选择的是确定按键");
                                layer.close(index);
                                document.getElementById('name').value=data.name;
                                document.getElementById('gender').value=data.gender;
                                document.getElementById('id_number').value=data.id_number;
                                document.getElementById('age').value=data.age;
                                document.getElementById('sbcard_id').value=data.sbcard_id;
                                document.getElementById('ybid').value=data.ybid;
                                document.getElementById('person_level').value=data.person_level;
                                document.getElementById('person_catagory').value=data.person_catagory;
                                document.getElementById('assess_type').value=data.assess_type;
                                document.getElementById('phone_number').value=data.phone_number;
                                document.getElementById('contact_people').value=data.contact_people;
                                document.getElementById('daiyu_start_date').value=data.daiyu_start_date;
                                document.getElementById('daiyu_due_date').value=data.daiyu_due_date;
                            },
                            error:function(){
                                layer.msg("删除机构信息出错")
                            }
                        })
                    })
                }
            });

            // 服务内容-树渲染
            var data2 = [{
                title: '基本生活照料（一）'
                ,id: 1
                ,checked: true
                ,children: [
                    {title: '头面部清洁、梳理',id: 5},
                    {title: '洗  发',id: 6},
                    {title: '指/趾甲护理',id: 7},
                    {title: '手、足部清洁',id: 8},
                    {title: '温水擦浴',id: 9},
                    {title: '沐  浴',id: 10},
                    {title: '协助进食/水',id: 11},
                    {title: '口腔清洁',id: 12},
                    {title: '协助更衣',id: 13},
                    {title: '整理床单位',id: 14},
                    {title: '排泄护理',id: 15},
                    {title: '失禁护理',id: 16},
                    {title: '床上使用便器',id: 17}
                ]
            },{
                title: '基本生活照料（二）'
                ,id: 2
                ,children: [
                    {title: '人工取便术',id: 18},
                    {title: '晨间护理',id: 19},
                    {title: '晚间护理',id: 20},
                    {title: '会阴护理',id: 21},
                    {title: '药物管理',id: 22},
                    {title: '协助翻身叩背排痰',id: 23},
                    {title: '协助床上移动',id: 24},
                    {title: '借助器具移动',id: 25},
                    {title: '皮肤外用药涂擦',id: 26},
                    {title: '安全护理',id: 27},
                    {title: '生活自理能力训练',id: 28},
                    {title: '压疮预防护理',id: 29},
                    {title: '留置尿管的护理',id: 30},
                    {title: '人工肛门便袋护理',id: 31}
                ]
            },{
                title: '常用临床护理（一）'
                ,id: 3
                ,children: [
                    {title: '开塞露/直肠栓剂给药',id: 32},
                    {title: '鼻  饲',id: 33},
                    {title: '药物喂服',id: 34},

                    {title: '物理降温',id: 35},
                    {title: '生命体征监测',id: 36},
                    {title: '吸  氧',id: 37},
                    {title: '灌  肠',id: 38}
                ]
            },{
                title: '常用临床护理（二）'
                ,id: 4
                ,children: [
                    {title: '导尿（女性）',id: 39},
                    {title: '血糖监测',id: 40},
                    {title: '压疮伤口换药',id: 41},
                    {title: '静脉血标本采集',id: 42},
                    {title: '肌肉注射',id: 43},
                    {title: '皮下注射',id: 44},
                    {title: '造口护理',id: 45},
                    {title: '经外周静脉置入中心|静脉导管（PICC）维护',id: 46}
                ]
            }];
            tree.render({
                elem:'#leftTree'
                ,id:'transfer'
                ,data: data2
                ,showCheckbox: true
            });

            //穿梭框内容
            var chosen=[];//用来存储选中项
            var contentRight=document.getElementById('contentRight');//与html的右穿梭框进行绑定
            var ul=document.createElement("ul"); //右穿梭框内容为列表结构
            util.event('lay-transfer', {
                //点击“右向左”按钮
                toRight: function(othis){
                    console.log("触发[左向右]传递事件");
                    //获取选中节点的数据
                    var checkedData = tree.getChecked('transfer');
                    //获取选中的服务项，并存入列表chosen中
                    if(chosen.length===0) {//倘若是第一次选中内容
                        for (var i = 0; i < checkedData.length; i++) {
                            for (var j = 0; j < checkedData[i].children.length; j++) {
                                console.log("初始无数据");
                                chosen.push(checkedData[i].children[j]); //将选中项push到新数组chosen中
                                //将选中项动态生成复选框，并显示在右边的穿梭框中
                                var index1=chosen.length;
                                var checkbox1=document.createElement("input");  //动态创建input语句的复选框
                                checkbox1.setAttribute("type","checkbox");
                                checkbox1.setAttribute("lay-skin","primary");
                                checkbox1.setAttribute("title",chosen[index1-1].title);
                                checkbox1.setAttribute("id",chosen[index1-1].id);
                                checkbox1.setAttribute("value",chosen[index1-1].title);
                                var li1=document.createElement("li");//创建li项
                                li1.appendChild(checkbox1);
                                ul.appendChild(li1);    //此处ul相对toRight函数为全局变量
                            }
                        }
                    }else{//倘若不是第一次选中内容，则需要判断选中内容是否重复，并对重复内容进行过滤
                        for (var m = 0; m < checkedData.length; m++) {
                            for (var n = 0; n < checkedData[m].children.length; n++) {
                                console.log("初始有数据");
                                //判断数据是否已经存在于chosen中
                                if(JSON.stringify(chosen).indexOf(JSON.stringify(checkedData[m].children[n]))===-1){
                                    console.log("无相同数据");
                                    chosen.push(checkedData[m].children[n]); //将选中项push到数组chosen中
                                    //将过滤后的选中项动态生成复选框，并显示在右边的穿梭框中
                                    var index2=chosen.length;
                                    console.log("chosen当前索引"+index2);
                                    var checkbox2=document.createElement("input");   //动态创建input语句的复选框
                                    checkbox2.setAttribute("type","checkbox");
                                    checkbox2.setAttribute("lay-skin","primary");
                                    checkbox2.setAttribute("title",chosen[index2-1].title);
                                    checkbox2.setAttribute("id",chosen[index2-1].id);
                                    checkbox2.setAttribute("value",chosen[index2-1].title);
                                    var li2=document.createElement("li");//创建li项
                                    li2.appendChild(checkbox2);
                                    ul.appendChild(li2);//此处ul相对toRight函数为全局变量，与前者使用的相同
                                }
                            }
                        }
                    }
                    console.log(chosen);
                    contentRight.appendChild(ul); //在与html绑定过的右穿梭框中插入ul列表，即已选项
                    form.render();//渲染，否则复选框无法显示
                },
                //点击“右向左”按钮
                toLeft:function(othis){
                    var storebox=[];
                    $('#contentRight [type=checkbox]:checked').each(function() {
                        storebox.push(this.id);//存储要已选中的要删除内容的ID
                    });
                    console.log(storebox);
                    //根据ID在chosen列表中进行删除
                    for(var i=0;i<storebox.length;i++){
                        for(var j=0;j<chosen.length;j++){
                            if(storebox[i]==chosen[j].id){
                                console.log("重复的ID:"+storebox[i]);
                                chosen.splice(j,1);
                            }
                        }
                    }
                    console.log("删除后的数组");
                    console.log(chosen);
                    //清空右穿梭框和ul中原来的内容，将当前chosen中的内容重新加载显示出来即可
                    contentRight.innerHTML='';
                    ul.innerHTML='';
                    //根据chosen中的内容，在右穿梭框进行显示
                    for(var row=0;row<chosen.length;row++){
                        console.log("进入动态删除功能");
                        var checkbox=document.createElement("input");  //动态创建input语句的复选框
                        checkbox.setAttribute("type","checkbox");
                        checkbox.setAttribute("lay-skin","primary");
                        checkbox.setAttribute("title",chosen[row].title);
                        checkbox.setAttribute("id",chosen[row].id);
                        checkbox.setAttribute("value",chosen[row].title);
                        var li=document.createElement("li");//创建li项
                        li.appendChild(checkbox);
                        ul.appendChild(li);    //此处ul相对toRight函数为全局变量
                    }
                    contentRight.appendChild(ul);
                    form.render();
                }
            });

            form.on('submit(handin)', function(){
                console.log("开始提交");
                var elderYbid=document.getElementById('ybid').value;
                var OrgSettleCode=document.getElementById('department_settlement_code').value;
                //存储选中服务项的具体内容
                var servContent=[];
                for(var index=0; index < chosen.length; index++){
                    servContent.push(chosen[index].title);
                }
                servContent=servContent.join();
                console.log("chosenContent：",servContent);
                //存储选中服务项的ID
                var servID=[];
                for(var index=0; index < chosen.length; index++){
                    servID.push(chosen[index].id);
                }
                servID=servID.join();
                console.log("chosenContent：",servContent);
                console.log("chosenContentID：",servID);
                console.log(elderYbid);
                console.log(OrgSettleCode);
                layer.confirm('是否确认提交', function(index) {
                    $.ajax({
                        url: '/arrangeInfo/newOrder',
                        method: 'POST',
                        data: {
                            elderYbid: elderYbid,
                            OrgSettleCode: OrgSettleCode,
                            servContent: servContent,
                            servID:servID
                        },
                        dataType: 'JSON',
                        success: function (res) {
                            console.log("res.msg：" + res.msg);
                            if (res.msg == "ok") {
                                console.log("成功提交");
                                layer.msg("提交成功", {icon: 1, time: 1500}, function () {
                                    layer.close(index);
                                    parent.location.reload();//提交成功后刷新父页面
                                });

                                // alert("提交成功");
                            } else {
                                console.log("提交错误");
                                layer.msg("请确保每项内容均已完成填写", {icon: 5, anim: 6, offset: "auto"});
                            }
                        },
                        error: function (data) {
                            console.log("提交失败", data);
                            layer.msg("提交出错", {icon: 5, anim: 6, offset: "auto"});
                        }
                    });
                });
                // return false;
            })
        });
    }
});